package com.hehui.partimejob.network;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.hehui.partimejob.service.vo.ServiceDataVo;
import com.hehui.partimejob.service.vo.ServiceListDataVo;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MyNetwork {
    private static MyNetwork mNetwork;
    private Context mContext;
    private RequestQueue mRequestQueue;
    public static final String BASE_URL = "http://10.0.2.2:8081";
    private static final String TAG = "MyNetwork";
    private final int OK = 200;
    private final int FAIL = 500;
    private static boolean isShowed = false;

    private MyNetwork() {
    }

    private MyNetwork(Context context) {
        this.mContext = context.getApplicationContext();
        mRequestQueue = Volley.newRequestQueue(mContext);
    }

    public static synchronized MyNetwork getInstance(Context context) {
        if (mNetwork == null) {
            mNetwork = new MyNetwork(context);
        }
        return mNetwork;
    }

    public <T> void get(String url, final OnNetworkListener<T> listener) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(BASE_URL + url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                NLog.Get("请求到的JSON" + response);
                if (response.optInt("code") == FAIL) {
                    Toast.makeText(mContext, response.optString("msg"), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (response.optInt("code") == OK) {
                    JsonArray data = JsonParser.parseString(response.optString("data")).getAsJsonArray();
                    Gson gson = new Gson();
                    Class<T> type = listener.getType();
                    ArrayList<T> ts = new ArrayList<>();
                    if (data.size() != 0) {
                        for (JsonElement datum : data) {
                            T t = gson.fromJson(datum, type);
                            ts.add(t);
                        }
                        ServiceListDataVo<T> serviceListDataVo = gson.fromJson(response.toString(), ServiceListDataVo.class);
                        serviceListDataVo.setData(ts);
                        listener.handleListData(serviceListDataVo);

                    } else {
                        listener.handleData(gson.fromJson(response.toString(), ServiceDataVo.class));
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "服务器开小差了", Toast.LENGTH_LONG).show();
                NLog.Get("onErrorResponse: " + error.getMessage());
                NLog.Get("onErrorResponse: " + error.getNetworkTimeMs());
            }
        });

        mRequestQueue.add(jsonObjectRequest);
        NLog.Get();
    }


    public <T> void post(String url, HashMap<String, Object> body, final OnNetworkListener<T> listener) {
        NLog.Post("发送的body" + new JSONObject(body).toString());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(BASE_URL + url, new JSONObject(body), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                NLog.Post("请求到的JSON" + response);
                if (response.optInt("code") == FAIL) {
                    Toast.makeText(mContext, response.optString("msg"), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (response.optInt("code") == OK) {
                    Class<T> type = listener.getType();
                    NLog.Post("请求到的类型 " + type.getSimpleName());
                    Gson gson = new Gson();
                    ServiceDataVo<T> dataVo = gson.fromJson(response.toString(), ServiceDataVo.class);
                    T data = gson.fromJson(response.optString("data"), type);
                    dataVo.setData(data);
                    listener.handleData(dataVo);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "服务器开小差了", Toast.LENGTH_LONG).show();
                NLog.Post("onErrorResponse: " + error.getMessage());
                NLog.Post("onErrorResponse: " + error.getNetworkTimeMs());
            }
        });
        mRequestQueue.add(jsonObjectRequest);
        NLog.Post();
    }


    private static class NLog {
        static void Get(String msg) {
            Log.d(TAG, "Get--------->: " + msg);
        }

        static void Get() {
            Get(null);
        }

        public static void Post(String msg) {
            Log.d(TAG, "Post--------->: " + msg);
        }

        public static void Post() {
            Post(null);
        }
    }
//    public static void bind(final Activity activity) {
//        getInstance(activity);
//        Class annotationParent = activity.getClass();
//        Field[] fields = annotationParent.getDeclaredFields();
//        Method[] methods = annotationParent.getDeclaredMethods();
//        // OnClick
//        // 找到类里面所有的方法
//        for (final Method method : methods) {
//            //找到添加了get注解的方法
//            Log.d(TAG, "bind: 找到添加了get注解的方法");
//            Get getMethod = method.getAnnotation(Get.class);
//            if (getMethod != null && !getMethod.url().isEmpty()) {
//                Class clazz = getMethod.dataType();
//                mNetwork.sendGetRequest( getMethod.url(), new OnNetworkListenerI() {
//                    @Override
//                    public void handleData(JsonArray jsonArray) {
//
//                    }
//
//                    @Override
//                    public void handleData(Gson gson, JSONObject data) {
//                        ServiceDataVo o = gson.fromJson(data.toString(), (Type) clazz);
//                        Log.d(TAG, "handleData: "+o);
//                        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
//                        for (Annotation[] parameterAnnotation : parameterAnnotations) {
//                            for (Annotation annotation : parameterAnnotation) {
//                                if (annotation instanceof ReturnData ) {
//
//                                }
//                            }
//                        }
//                    }
//                });
//
//            }
//        }
//
//    }


}
